package mx.unam.fciencias.ppc.beansboard.comm;

import java.net.*;
import java.io.*;
import java.util.Scanner;

/**
 *
 * @author lander
 */
public final class CollabServiceClient extends CollabService implements Runnable {

    private InetAddress address;
    private int port;
    private String user;
    private Socket socket;
    private PrintWriter pw;
    private Scanner sc;

    public CollabServiceClient(InetAddress address, int port, String user) {
        this.address = address;
        this.port = port;
        this.user = user;
    }

    /**
     * Message sent to the client via <code>PrintWriter</code>
     * @param message Message to be sent
     */
    public void sendMessage(String message) {
        pw.println(message);
        System.out.println("Message sent: "+message);
    }

    public void lockF(String user, String file, int line) {
        System.out.println("The user: " + user + " has locked line " + line + " in file: " + file);
    }

    public void unlockF(String user, String file, int line) {
        System.out.println("The user: " + user + " has unlocked line " + line + " in file: " + file);
    }

    public void run() {
        try {
            socket = new Socket(address, port);
            pw = new PrintWriter(socket.getOutputStream());
            sc = new Scanner(socket.getInputStream());
            sendMessage(login(user));
        } catch (IOException ioe) {
            System.err.println("Error creating socket: " + ioe.getMessage());
        }
        while (!socket.isClosed()) {
            String s = sc.nextLine();
            String[] tokens = s.split(CollabService.DELIMITER);
            int c = Integer.parseInt(tokens[0]);
            switch (c) {
                case LOCK:
                    lockF(sc.next(), sc.next(), Integer.parseInt(sc.next()));
                case UNLOCK:
                    unlockF(sc.next(), sc.next(), Integer.parseInt(sc.next()));
                default:

            }
        }
    }
}
